package com.lzj.server.common.log;

import com.lzj.server.common.model.Log;
import com.lzj.server.common.service.LogService;
import com.lzj.server.utils.LogUtils;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBlockingQueue;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class LogQueueConsumer {

    @Resource
    private LogService logService;

    private RBlockingQueue<Log> queue;

    @PostConstruct
    public void startLogConsumer() {
        // 初始化队列，避免每次循环都调用
        queue = LogUtils.getLogQueue();
        new Thread(() -> {
            // 使用线程中断机制来控制循环
            while (!Thread.currentThread().isInterrupted()) {
                try {
                    Log log = queue.take();
                    logService.save(log);
                } catch (InterruptedException e) {
                    // 恢复中断状态
                    Thread.currentThread().interrupt();
                    System.out.println("Log-Queue-Consumer 已被中断");
                } catch (Exception e) {
                   log.error("Log-Queue-Consumer Error", e);
                }
            }
        }, "Log-Queue-Consumer").start();
    }
}
